"""回合制战斗游戏主程序"""

import json
from game.game_manager import GameManager
from utils.json_encoder import format_battle_result, save_battle_result


def print_separator(title: str = ""):
    """打印分隔线"""
    print("=" * 60)
    if title:
        print(f" {title} ")
        print("=" * 60)


def print_battle_state(game_manager: GameManager):
    """打印战斗状态"""
    state = game_manager.get_battle_state()
    if state:
        print(f"战斗ID: {state['battle_id']}")
        print(f"状态: {state['status']}")
        print(f"当前回合: {state['current_round']}")
        
        print("\n玩家方角色:")
        for char in state['player_characters']:
            print(f"  {char['name']} (ID: {char['id']}) - HP: {char['hp']} - 位置: ({char['position']['x']}, {char['position']['y']}) - 存活: {char['is_alive']}")
        
        print("\n敌方角色:")
        for char in state['enemy_characters']:
            print(f"  {char['name']} (ID: {char['id']}) - HP: {char['hp']} - 位置: ({char['position']['x']}, {char['position']['y']}) - 存活: {char['is_alive']}")


def demo_auto_battle():
    """演示自动战斗"""
    print_separator("自动战斗演示")
    
    game_manager = GameManager()
    
    print("正在设置战斗...")
    battle_result = game_manager.run_auto_battle()
    
    print(f"\n战斗ID: {battle_result['battle_id']}")
    print(f"总回合数: {len(battle_result['rounds'])}")
    
    # 显示每回合的行动
    for round_data in battle_result['rounds']:
        print(f"\n第 {round_data['round_number']} 回合:")
        for action in round_data['actions']:
            print(f"  {action['character_id']} 使用 {action['skill_id']} 攻击位置 ({action['target']['x']}, {action['target']['y']})")
            for effect in action['effects']:
                effect_type = "伤害" if effect['effect_type'] == 'damage' else "治疗"
                print(f"    -> {effect['target_id']} 受到 {effect['value']} 点{effect_type}")
    
    # 显示最终结果
    if battle_result['final_result']:
        final = battle_result['final_result']
        winner = "玩家方" if final['winner'] == 'player' else "敌方"
        print(f"\n战斗结束！获胜方: {winner}")
        
        # 保存结果到文件
        filename = f"battle_result_{battle_result['battle_id']}.json"
        if save_battle_result(final, filename):
            print(f"战斗结果已保存到: {filename}")
    
    return battle_result


def demo_manual_battle():
    """演示手动战斗"""
    print_separator("手动战斗演示")
    
    game_manager = GameManager()
    
    print("正在设置战斗...")
    battle_result = game_manager.run_manual_battle_demo()
    
    print(f"\n战斗ID: {battle_result['battle_id']}")
    print(f"执行的行动数: {len(battle_result['actions'])}")
    
    # 显示每个行动
    for i, action in enumerate(battle_result['actions'], 1):
        print(f"\n行动 {i}:")
        print(f"  {action['character_id']} 使用 {action['skill_id']} 攻击位置 ({action['target']['x']}, {action['target']['y']})")
        for effect in action['effects']:
            effect_type = "伤害" if effect['effect_type'] == 'damage' else "治疗"
            print(f"    -> {effect['target_id']} 受到 {effect['value']} 点{effect_type}")
    
    # 显示最终结果
    if battle_result.get('final_result'):
        final = battle_result['final_result']
        winner = "玩家方" if final['winner'] == 'player' else "敌方"
        print(f"\n战斗结束！获胜方: {winner}")
    
    return battle_result


def demo_custom_battle():
    """演示自定义战斗"""
    print_separator("自定义战斗演示")
    
    game_manager = GameManager()
    
    # 自定义角色数据
    player_data = [
        {"name": "圣骑士", "hp": 150, "attack": 22, "defense": 18, "speed": 10, "x": 0, "y": 1},
        {"name": "弓箭手", "hp": 90, "attack": 35, "defense": 8, "speed": 22, "x": 1, "y": 0},
        {"name": "牧师", "hp": 100, "attack": 12, "defense": 10, "speed": 18, "x": 1, "y": 2}
    ]
    
    enemy_data = [
        {"name": "兽人酋长", "hp": 180, "attack": 28, "defense": 15, "speed": 8, "x": 3, "y": 1},
        {"name": "兽人萨满", "hp": 120, "attack": 25, "defense": 12, "speed": 15, "x": 2, "y": 0},
        {"name": "兽人战士", "hp": 130, "attack": 24, "defense": 14, "speed": 12, "x": 2, "y": 2}
    ]
    
    print("正在创建自定义战斗...")
    battle_id = game_manager.create_custom_battle(player_data, enemy_data)
    
    print(f"战斗创建成功！战斗ID: {battle_id}")
    print_battle_state(game_manager)
    
    print("\n开始自动战斗...")
    battle_result = game_manager.run_auto_battle(battle_id)
    
    # 显示简化的战斗结果
    print(f"\n战斗完成！总回合数: {len(battle_result['rounds'])}")
    if battle_result['final_result']:
        final = battle_result['final_result']
        winner = "玩家方" if final['winner'] == 'player' else "敌方"
        print(f"获胜方: {winner}")
    
    return battle_result


def show_available_skills():
    """显示可用技能"""
    print_separator("可用技能列表")
    
    game_manager = GameManager()
    skills = game_manager.get_available_skills()
    
    for skill_id, skill_data in skills.items():
        print(f"技能ID: {skill_id}")
        print(f"  名称: {skill_data['name']}")
        print(f"  类型: {skill_data['type']}")
        print(f"  目标类型: {skill_data['target_type']}")
        print(f"  基础数值: {skill_data['base_value']}")
        print(f"  作用范围: {skill_data['range_size']}")
        print(f"  描述: {skill_data['description']}")
        print()


def main():
    """主函数"""
    print_separator("回合制战斗游戏演示")
    print("这是一个回合制战斗游戏的后端演示程序")
    print("包含角色系统、战场布局、技能系统和战斗逻辑")
    
    try:
        # 显示可用技能
        show_available_skills()
        
        # 演示自动战斗
        auto_result = demo_auto_battle()
        
        # 演示手动战斗
        manual_result = demo_manual_battle()
        
        # 演示自定义战斗
        custom_result = demo_custom_battle()
        
        print_separator("演示完成")
        print("所有演示已完成！")
        print("战斗结果已以JSON格式输出，可以在生成的文件中查看详细信息。")
        
    except Exception as e:
        print(f"演示过程中发生错误: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    main()